package com.common.frame.utils;

import android.content.Intent;
import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;


import com.common.frame.bean.ActivityResult;

import java.util.Random;

import io.reactivex.Single;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.subjects.SingleSubject;

/**
 * - 跳转activity并接受返回值。
 * Created by Sunxy
 */
public class StartActForResultUtils extends Fragment {

    private SingleSubject<ActivityResult> mSubject;
    private int startRequestCode;
    private Disposable dis;


    public static StartActForResultUtils getFragment(Fragment fragment){
        return generateFragment(fragment.getChildFragmentManager());
    }

    public static StartActForResultUtils getFragment(AppCompatActivity activity){
        return generateFragment(activity.getSupportFragmentManager());
    }

    /**
     * 生成 Fragment
     */
    private static StartActForResultUtils generateFragment(FragmentManager fragmentManager){
        if (fragmentManager == null){
            return new StartActForResultUtils();
        }
        StartActForResultUtils fragment = (StartActForResultUtils) fragmentManager.findFragmentByTag("StartActForResultUtils");
        if (fragment == null){
            fragment = new StartActForResultUtils();
            fragmentManager.beginTransaction().add(fragment, "StartActForResultUtils").commitAllowingStateLoss();
            fragmentManager.executePendingTransactions();
        }
        return fragment;
    }

    /**
     * 跳转
     */
    public Single<ActivityResult> start(Class clazz, Bundle bundle) {
        Intent intent = new Intent(getContext(), clazz);
        if (bundle != null){
            intent.putExtras(bundle);
        }
        return start(intent);
    }

    /**
     * 跳转
     */
    public Single<ActivityResult> start(final Intent intent) {
        if (dis != null && !dis.isDisposed()) dis.dispose();
        this.startRequestCode = new Random().nextInt(1000) + 10000;
        mSubject = SingleSubject.create();
        return mSubject.doOnSubscribe(new Consumer<Disposable>() {
            @Override
            public void accept(Disposable disposable) throws Exception {
                dis = disposable;
                startActivityForResult(intent, startRequestCode);
            }
        }).observeOn(AndroidSchedulers.mainThread());
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRetainInstance(true);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (dis != null && !dis.isDisposed()) dis.dispose();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mSubject != null){
            if (startRequestCode == requestCode){
                mSubject.onSuccess(new ActivityResult(requestCode, resultCode, data));
            }
        }
    }

}
